package com.example.JcGQS.ElasticsearchApiExample;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.JcGQS.pojo.entity.Goods;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * ES
 * @author 末日
 * @date 2023/11/21
 */
@Component
public class ElasticsearchApiExample {
    // 设置 Elasticsearch 节点的地址和端口
    private static final String elasticsearchHost = "localhost";
    private static final int elasticsearchPort = 9200;
    // 设置索引名称
    private static final String indexName = "goods";

    /**
     * 每次启动时运行一次创建索引,如若第二次或这二次以后运行时让其报错并捕获(报错没事!!)
     */
    static {
    try {
        createIndex();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

    /**
     * 创建索引
     */
    public static void createIndex() throws IOException {
        URL url = new URL("http://" + elasticsearchHost + ":" + elasticsearchPort + "/" + indexName);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("PUT");

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }

           // System.out.println("Index created successfully. Response: " + response.toString());
        } finally {
            connection.disconnect();
        }
    }


    /**
     * 新增ES数据
     * @param Id    标志id
     * @throws IOException
     */
    public void insertData(Integer Id, JSONObject jsonObject) throws IOException {
        URL url = new URL("http://" + elasticsearchHost + ":" + elasticsearchPort + "/" + indexName + "/_doc/" + Id);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);

        String data = jsonObject.toString();

        try (OutputStream os = connection.getOutputStream()) {
            os.write(data.getBytes());
        }
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            //System.out.println("Document created successfully. Response: " + response.toString());
        } finally {
            connection.disconnect();
        }
    }

    /**
     * 删除ES数据
     *
     * @param documentId 标志id
     * @throws IOException
     */
    public void deleteData(Integer documentId) throws IOException {
        URL url = new URL("http://" + elasticsearchHost + ":" + elasticsearchPort + "/" + indexName + "/_doc/" + documentId);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("DELETE");
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
           // System.out.println("Document deleted successfully. Response: " + response.toString());
        } finally {
            connection.disconnect();
        }
    }

    /**
     * 全局搜索
     *
     * @param searchKeyword 搜索内容
     * @throws IOException
     */
    public String globalSearch(String searchKeyword) throws IOException {

        // 去除开头和结尾的空格
        searchKeyword = searchKeyword.trim();
        // 构建查询字符串
//        String queryString = "{\"query\": {\"query_string\": {\"query\": \"*" + searchKeyword + "*\"}}}";
        String queryString = "{\"query\": {\"query_string\": {\"query\": \"*" + searchKeyword + "*\"}}, \"size\": 9999}";

        URL url = new URL("http://" + elasticsearchHost + ":" + elasticsearchPort + "/" + indexName + "/_search");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);

        try (OutputStream os = connection.getOutputStream()) {
            os.write(queryString.getBytes());
        }

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
           // System.out.println("Search results: " + response.toString());

            return response.toString();
        } finally {
            connection.disconnect();
        }
    }
}